<template>
  <div
    class="config-wrapper"
    v-loading.fullscreen.lock="loading && navIndex === 1"
  >
    <!-- 门户导航栏-->
    <ConfigNavbar
      ref="configNavbarRef"
      :template-name="templateName"
      :nav-index="navIndex"
      :type-id="typeId"
      @handleToggleNav="handleToggleNav"
      @save="save"
      @back="back"
    />

    <PortalConfig
      ref="portalConfigRef"
      v-if="navIndex === 1"
      :tenant-id="tenantId"
      :type-id="typeId"
      :template-name="templateName"
      :theme-colour="themeColour"
      :language-list="languageList"
      :need-server-dele-files="needServerDeleFiles"
      @updateState="changeLoadingState"
    />
    <PortalStyle
      v-else
      ref="portalStyleRef"
      :type-id="typeId"
      :theme-colour="themeColour"
      :tab-bar-list="tabBarList"
    />
  </div>
</template>

<script>
import {
  ref,
  computed,
  nextTick,
  onMounted,
  reactive,
  toRefs,
  provide,
} from 'vue';
import ConfigNavbar from '../components/configNavbar.vue';
import PortalStyle from '../components/portalStyle.vue';
import PortalConfig from '../components/portalConfig.vue';
// import { useConfigNav } from '@hooks/portal/useConfig.ts';
import { getRootWindowInitData } from '@src/util/window';
import qs from '@src/util/querystring';
import { PortalTabbarEnum, PortalNavbarEnum } from '@model/types/PortalConfig';
import { Message, MessageBox } from 'element-ui';
import { getDoorTypeInfo } from '@src/api/PortalApi.ts';
import i18n, { transformI18n } from '@src/locales/index.ts';
import { getAttachmentIdByUrl } from 'pub-bbx-utils'

export default {
  components: {
    ConfigNavbar,
    PortalConfig,
    PortalStyle,
  },
  setup() {
    const loading = ref(true);
    const configNavbarRef = ref(null);
    const portalConfigRef = ref(null);
    const portalStyleRef = ref(null);
    const tabbarsIndex = ref(PortalTabbarEnum.Home);
    const navIndex = ref(PortalNavbarEnum.Config);

    const portalInfo = reactive({
      themeColour: '',
      languageList: [],
      tabBarList: {},
      // templateName: '',
      doorNameLanguage: {},
      needServerDeleFiles:  [], // 需要删除的服务器文件
    });

    const rootWindowInitData = getRootWindowInitData();
    const queryObject = qs.parse(window.location.search);

    const handleToggleNav = index => {
      // 门户配置页面切换需要校验，需要保存提示
      if (index === PortalNavbarEnum.Style) {
        if (portalConfigRef.value?.handleCheckSave()) {
          return navIndex.value = index;
        } 

        tabbarsIndex.value = portalConfigRef.value?.checkedTabbarIndex;
        const result = portalConfigRef.value?.handleToggleTabbar(
          tabbarsIndex.value
        );
        if (!result) return
        
      } else {
        if (portalStyleRef.value?.handleCheckSave()) {
          loading.value = true;
          navIndex.value = index;
          nextTick(() => {
            portalConfigRef.value?.handleToggleTabbar(tabbarsIndex.value);
          });
          return;
        }
      }

      MessageBox.confirm(i18n.t('portal.portalTip8'), i18n.t('common.base.toast'), {
        confirmButtonText: i18n.t('common.base.confirm'),
        cancelButtonText: i18n.t('common.base.cancel'),
        type: 'warning',
      })
        .then(() => {
          navIndex.value = index;
          nextTick(() => {
            portalConfigRef.value?.handleToggleTabbar(tabbarsIndex.value);
          });
        })
        .catch(() => {
          //
        });
    };

    const tenantId = computed(() => {
      return (
        rootWindowInitData?.user?.tenantId
        || '7416b42a-25cc-11e7-a500-00163e12f748'
      );
    });

    const typeId = computed(() => {
      return queryObject.id ?? '';
    });

    const templateName = computed(() => {
      return transformI18n(portalInfo.doorNameLanguage, i18n.locale);
    });

    const save = async isRelease => {
      let result;
      if (navIndex.value === PortalNavbarEnum.Config) {
        try {
          result = await portalConfigRef.value.save(isRelease);
        } catch (error) {
          console.warn(error, 'error try catch portalConfigRef');
        }
        
      } else {
        try {
          result = await portalStyleRef.value.save(isRelease);
        } catch (error) {
          console.warn(error, 'error try catch portalStyleRef');
        }
      }

      configNavbarRef.value.saveLoading = false;
      configNavbarRef.value.releaseLoading = false;

      if (result) {
        Message({
          message: isRelease
            ? i18n.t('portal.portalTip9')
            : i18n.t('common.base.saveSuccess'),
          type: 'success',
          duration: 2000,
        });

        sessionStorage.removeItem('doorTypeFieldVOS');
        if (isRelease) {
          setTimeout(() => {
            window.history.back();
          }, 1000);
        } else {
          setTimeout(() => {
            window.location.reload();
          }, 1000);
        }
      } else {
        // Message({
        //   message: isRelease ? i18n.t('portal.publishFailure') : i18n.t('common.base.saveFail'),
        //   type: 'error',
        //   duration: 2000,
        // });
      }
    };

    const back = () => {
      if (typeId) {
        sessionStorage.setItem('_doorId', typeId.value);
      }
      if (navIndex.value === PortalNavbarEnum.Config) {
        portalConfigRef.value.handleBack();
      } else {
        portalStyleRef.value.handleBack();
      }
    };

    const changeLoadingState = value => {
      loading.value = value;
    };

    // 获取指定模版信息
    const _getDoorTypeInfo = async () => {
      try {
        const id = typeId.value;
        if (!id) return;

        const { code, data } = await getDoorTypeInfo({ id });
        if (code !== '200') return;

        portalInfo.themeColour = data?.setting?.doorStyle?.themeColourDraft || '';
        portalInfo.languageList = data?.setting?.language || [];
        portalInfo.tabBarList = data?.setting?.doorNavigation || {};
        portalInfo.doorNameLanguage = data?.setting?.doorNameLanguage || {};
        portalInfo.needServerDeleFiles = data?.deleteFiles || [];
        // portalInfo.templateName = data?.typeName || '';
      } catch (error) {
        console.error('getDoorTypeInfo error', error);
      }
    };
    const addNeedServerDeleFiles = (files, needChange = true)=>{
      files?.map(val=>{
        // 直接传id过来
        if(!needChange) return portalInfo.needServerDeleFiles.push(val)

        const fileId = getAttachmentIdByUrl(val)
        fileId && portalInfo.needServerDeleFiles.push(fileId)
      })
    }
    provide('addNeedServerDeleFiles', addNeedServerDeleFiles)

    onMounted(() => {
      _getDoorTypeInfo();
    });

    return {
      loading,
      configNavbarRef,
      portalConfigRef,
      portalStyleRef,
      tenantId,
      typeId,
      navIndex,
      templateName,
      ...toRefs(portalInfo),
      handleToggleNav,
      save,
      back,
      changeLoadingState,
    };
  },
};
</script>

<style lang="scss" scoped>
@import '../index';

.config-wrapper {
  @include box-setting(100%, 100vh, #ffffff);
}
</style>
